﻿using DrmEdiCS;

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

using static System.Net.Mime.MediaTypeNames;

namespace ExcelSLN.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class CommonController : ApiController
    {
        /// <summary>
        /// 测试文件解析
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string ResolveEncrypt(string encryptedFilePath)
        {
            try
            {

                CDrmEdiCS.SDKInit("http://api-gw.hisense.com/drm", "16d773d6", "cb3bae88125ad65a6843e3bc42653b72");

                if (!System.IO.File.Exists(encryptedFilePath))
                {
                    return "加密文件不存在";
                }
                else
                {
                    bool flag = CDrmEdiCS.IsEncryptedDrmFile($@"{encryptedFilePath}");
                    int num = CDrmEdiCS.DecryptDrmFile($@"{encryptedFilePath}", "test1");

                    //HttpFileCollection files = HttpContext.Current.Request.Files;
                    //if (files.Count > 0)
                    //{
                    //    HttpPostedFile httpPostedFile = files[0];
                    //    string extension = Path.GetExtension(files[0].FileName);
                    //    FileInfo fileInfo = new FileInfo(httpPostedFile.FileName);
                    //    string text = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "import");
                    //    if (!Directory.Exists(text))
                    //    {
                    //        Directory.CreateDirectory(text);
                    //    }
                    //    httpPostedFile.SaveAs(Path.Combine(text, httpPostedFile.FileName));
                    //    CDrmEdiCS.SDKInit("http://api-gw.hisense.com/drm", "16d773d6", "cb3bae88125ad65a6843e3bc42653b72");
                    //    flag = CDrmEdiCS.IsEncryptedDrmFile(Path.Combine(text, httpPostedFile.FileName));
                    //    if (flag)
                    //    {
                    //        num = CDrmEdiCS.DecryptDrmFile(Path.Combine(text, httpPostedFile.FileName), "test1");
                    //    }
                    //    return Path.Combine(text, httpPostedFile.FileName);
                    //}
                    return $"{flag}-{num}";
                }
            }
            catch (Exception EX)
            {
                return EX.StackTrace + EX.Message;
            }
        }

        /// <summary>
        /// EXCEL解析
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public object ResolveExcel()
        {
            DataTable dt = new DataTable();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TEMP1", Guid.NewGuid().ToString() + ".xlsx");
                files[0].SaveAs(filePath);
                CDrmEdiCS.SDKInit("http://api-gw.hisense.com/drm", "16d773d6", "cb3bae88125ad65a6843e3bc42653b72");
                bool flag = CDrmEdiCS.IsEncryptedDrmFile(filePath);
                if (flag)
                {
                    int num = CDrmEdiCS.DecryptDrmFile(filePath, "test1");
                    if (num != 0)
                    {
                        throw new Exception("无法解密该文件，返回值为：" + num.ToString());
                    }
                }
                dt = MExcel.Resolve(filePath);
            }

            return new { data = dt, code = 0, msg = "success" };
        }
        /// <summary>
        /// 根据base64位进行excel解析
        /// </summary>
        /// <param name="uploadInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public object ResolveExcelByBase64(uploadInfo uploadInfo)
        {
            MemoryStream fileInfo = new MemoryStream(Convert.FromBase64String(uploadInfo.contents));
            var buf = fileInfo.ToArray();
            //file = System.Web.HttpContext.Current.Server.MapPath("~/temp/") + Guid.NewGuid() + ".xlsx";
            //保存为Excel文件
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TEMP1", Guid.NewGuid().ToString() + ".xlsx");
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
            CDrmEdiCS.SDKInit("http://api-gw.hisense.com/drm", "16d773d6", "cb3bae88125ad65a6843e3bc42653b72");
            bool flag = CDrmEdiCS.IsEncryptedDrmFile(filePath);
            if (flag)
            {
                int num = CDrmEdiCS.DecryptDrmFile(filePath, "test1");
                if (num != 0)
                {
                    throw new Exception("无法解密该文件，返回值为：" + num.ToString());
                }
            }
            DataTable dt = MExcel.Resolve(filePath);
            return new { data = dt, code = 0, msg = "success" };
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        [HttpPost]
        public string UploadFile(string path)
        {
            //
            //FileInfo fileInfo = new FileInfo(file.FileName);
            //fileInfo.CopyTo(filePath, true);
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files");
            if (string.IsNullOrEmpty(path) == false)
            {
                filePath = Path.Combine(filePath, path);
            }
            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);
            }
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                using (var stream = new FileStream(Path.Combine(filePath, files[0].FileName), FileMode.Create))
                {
                    files[0].SaveAs(Path.Combine(filePath, files[0].FileName));
                }
                if (string.IsNullOrEmpty(path) == false)
                {
                    return Path.Combine(path, files[0].FileName);
                }
                else
                {
                    return files[0].FileName;
                }
            }
            return String.Empty;
        }


    }
    /// <summary>
    /// 
    /// </summary>
    public class uploadInfo
    {
        public string name { get; set; }
        public string type { get; set; }
        public string contents { get; set; }

    }
}
